<?php

namespace App\Http\Controllers\Admin\Logs;

use App\Http\Controllers\AdminController;
use Carbon\Carbon;
use Spatie\Activitylog\Models\Activity;
use Illuminate\Http\Request;
use App\Models\System\User;

class ActivityController extends AdminController
{
    public function data(Request $request)
    {
        $model = Activity::query()->select(['id', 'log_name', 'description', 'subject_type', 'properties', 'causer_id', 'created_at']);
        if ($logName = $request->get('logName')) {
            $model->where('log_name', $logName);
        }
        if ($subjectType = $request->get('subjectType')) {
            $model->where('subject_type', $subjectType);
        }
        if ($userId = $request->get('userId')) {
            $model->where('causer_type', User::class)->where('causer_id', (int)$userId);
        }
        $total = $model->count();
        $page = (int)$request->get('page', 1);
        $pageSize = (int)$request->get('pageSize', 10);
        $list = $model->orderByDesc('id')->offset(($page-1)*$pageSize)->limit($pageSize)->get()->toArray();
        $users = User::query()->pluck('display_name', 'id');
        if (!empty($list)) {
            foreach ($list as $key => $row) {
                $list[$key]['causer_name'] = $users[$row['causer_id']];
                $list[$key]['created_at'] = Carbon::parse($row['created_at'])->format('Y-m-d H:i:s');
            }
        }
        return $this->succeed([
            'total' => $total,
            'rows' => $list,
        ]);
    }
}
